/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * 
 * @author billy zhang
 * 
 */
@ControllerAdvice
public class WebErrorHandler implements TemplateExceptionHandler {
	
	private static Logger logger = LoggerFactory.getLogger(WebErrorHandler.class);

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ModelAndView methodNotSupportedHandler(
    		HttpServletRequest req, Exception e) {

		logger.error("出错啦！", e);

		try {
			 AdminHelper helper = (AdminHelper)req.getAttribute(Constants.ADMIN_HELPER);
	        if (helper == null) {
	        	helper = new AdminHelper();
	        	req.setAttribute(Constants.ADMIN_HELPER, helper);
	        }
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
        
		ModelAndView mv = new ModelAndView();
		mv.setStatus(HttpStatus.METHOD_NOT_ALLOWED);
		mv.setViewName("error405");
		
		return mv;
    }

	@ExceptionHandler(value = Exception.class)
	public ModelAndView defaultHandler(HttpServletRequest req, Exception e) {

		logger.error("出错啦！", e);
		
		try {

	        AdminHelper helper = (AdminHelper)req.getAttribute(Constants.ADMIN_HELPER);
	        if (helper == null) {
	        	helper = new AdminHelper();
	        	req.setAttribute(Constants.ADMIN_HELPER, helper);
	        }

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
        
		ModelAndView mv = new ModelAndView();
		mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
		
		mv.addObject("exception", e.toString());
		mv.addObject("url", req.getRequestURL());
		mv.setViewName("error50x");
		
		return mv;
	}
	
	@Override
    public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
	    logger.error("[出错了，请联系网站管理员]", te);
    }
}
